"""8.2 实现集成外部mcp服务npx类型"""
import asyncio
import json
from contextlib import AsyncExitStack

from mcp import StdioServerParameters, stdio_client, ClientSession
from openai import OpenAI


class MCPClient:



    def __init__(self):
        self.async_exit_stack = AsyncExitStack()
        self.session = None
        self.deepseek = OpenAI(
            api_key="sk-15af4e21f828460683b16ce9e78b2346",
            base_url="https://api.deepseek.com"
        )


    async def connect_to_server(self,server_path):
        # 一、创建服务连接的参数
        server_parameters = StdioServerParameters(
            command="npx",
            args=[
                "-y",
                 "@modelcontextprotocol/server-filesystem",
                 "D:\\dir_test"
            ],
            env=None
        )
        # 二、创建stdio_client
        client = stdio_client(server_parameters)
        transport = await self.async_exit_stack.enter_async_context(client)
        read_stream, write_stream = transport
        # 三、创建会话client
        client_session = ClientSession(read_stream, write_stream)
        self.session = await self.async_exit_stack.enter_async_context(client_session)
        # 四、初始化会话
        await self.session.initialize()

    async def execute(self,query:str):
        # 一、获取server.py中的工具列表
        response = await self.session.list_tools()
        list_tools = response.tools
        print("打印出获取的工具列表：",list_tools)
        #二、创建function calling 格式(大模型使用）、
        tools =[
            {
                "type":"function",
                "function":{
                    "name":tool.name,
                    "description":tool.description,
                    "parameters":tool.inputSchema
                }
            } for tool in list_tools
        ]
        # 三、 创建messages,deepseek大模型的格式
        messages = [
            {
                "role":"user",
                "content":query
            }
        ]
        # 四、调用deepseek大模型
        deepseek_response = self.deepseek.chat.completions.create(
            model="deepseek-chat",
            messages=messages,
            tools=tools
        )
        # 打印出大模型的决策结果
        print("==== deepseek 响应持结果：",deepseek_response)
        choice_result = deepseek_response.choices[0]
        #第二次调用大模型的前置参数
        messages.append(choice_result.message.model_dump())
        tool_call = choice_result.message.tool_calls[0]

        print(" tool_call:",tool_call)
        print("大模型决策的最终结果,工具名称：",tool_call.function.name,",参数：",tool_call.function.arguments)
        function_name = tool_call.function.name
        arguments = json.loads(tool_call.function.arguments)
        # 五、调用工具链
        tool_result = await self.session.call_tool(
            name = function_name,
            arguments=arguments
        )
        print("==== 工具调用结果：",tool_result)
        #最终的结果
        result = tool_result.content[0].text
        print("==== 最终的结果：",result)

        # 六、使用大模型生成最终的结果，并且使用语言模型生成最终的结果
        messages.append({
            "role": "tool",
            "content": tool_result.content[0].text,
            "tool_call_id": tool_call.id
        })
        # 再次调用大模型
        deepseek_response = self.deepseek.chat.completions.create(
            model="deepseek-chat",
            messages=messages,
            tools=tools,
        )
        # 获取最终的结果
        result = deepseek_response.choices[0].message.content
        print("==== 最终的结果：", result)


    #关闭资源
    async def aclose(self):
        await self.async_exit_stack.aclose()

async def main():
    client = MCPClient()
    try:
        await client.connect_to_server("server.py")
        await client.execute("在目录文件中D:\dir_test\\test10.txt（目录已经存在）,写入hello world")
    except Exception as e:
        print(f"连接失败: {e}")
        return
    finally:
        await client.aclose()

if __name__ == "__main__":
    asyncio.run(main())